package com.cw.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;

/**
 * @program: MySyetem
 * @description: Jwt工具类
 * @author: 张庆恒
 * @create: 2021-08-28 14:49
 **/
public class JwtUtils {
    public static  String createToken(Integer userId,String realName,String userName,String imgUrl,Integer roleid) {
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, 30);
        Date expiresDate = nowTime.getTime();
        return JWT.create().withAudience(userId + "")
                .withIssuedAt(new Date())
                .withExpiresAt(expiresDate)
                .withClaim("userName", userName)
                .withClaim("relName", realName)
                .withClaim("imgUrl", imgUrl)
                .withClaim("roleid", roleid)
                .sign(Algorithm.HMAC256("ZQH"));
    }
    public static void verifyToken(String token)throws Exception {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256("ZQH")).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            throw new Exception();
        }
    }
    public static String getAudience(String token)throws Exception {
        String audience = null;
        try {
            audience = JWT.decode(token).getAudience().get(0);
        } catch (Exception e) {
            throw new Exception();
        }
        return audience;
    }

    public static Claim getClaimByName(String token, String name) {
        return JWT.decode(token).getClaim(name);
    }
}


